package com.example.treehole.ui.page.treehole

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.treehole.LocalNavController
import com.example.treehole.LocalPostListViewModel
import com.example.treehole.LocalUserViewModel
import com.example.treehole.ui.component.SearchBox
import com.example.treehole.ui.theme.Cyan
import kotlinx.coroutines.launch

@Composable
fun TreeholeScreen() {
    val userViewModel = LocalUserViewModel.current
    val userId by userViewModel.userId.collectAsState()
    val jwlToken by userViewModel.jwlToken.collectAsState()
    val scope = rememberCoroutineScope()

    val postListViewModel = LocalPostListViewModel.current

    val tabTitles = listOf("最新", "热门", "收藏")
    val pagerState = rememberPagerState(pageCount = { tabTitles.size })
    val navController = LocalNavController.current
    val searchText = remember { mutableStateOf("") }
    val searchMode = remember { mutableStateOf(false) }
    val density = LocalDensity.current.density
    val screenWidth = LocalConfiguration.current.screenWidthDp * density
    val screenHeight = LocalConfiguration.current.screenHeightDp * density
    var fabPosition by remember {
        mutableStateOf(
            Offset(
                x = screenWidth - 100 * density,
                y = screenHeight - 250 * density
            )
        )
    }

    BackHandler(searchMode.value) { searchMode.value = false }

    Column(modifier = Modifier.fillMaxSize()) {
        // 搜索框
        SearchBox(
            searchMode = searchMode,
            searchText = searchText,
            onSearch = {
                scope.launch {
                    userId?.let { postListViewModel.searchPost(jwlToken, searchText.value, it) }
                }
            }
        )
        if (!searchMode.value) {
            TabRow(
                selectedTabIndex = pagerState.currentPage,
                containerColor = Color.Transparent,
                indicator = { tabPositions ->
                    TabRowDefaults.PrimaryIndicator(
                        color = Cyan,
                        height = 4.dp,
                        width = 40.dp,
                        modifier =
                        Modifier
                            .tabIndicatorOffset(
                                tabPositions[pagerState.currentPage]
                            )
                            .background(
                                color = Color.Transparent,
                                shape = RoundedCornerShape(2.dp)
                            ),
                    )
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 0.dp),
                divider = { HorizontalDivider(color = Color.Transparent) }
            ) {
                tabTitles.forEachIndexed { index, title ->
                    val isSelected = pagerState.currentPage == index
                    Tab(
                        text = {
                            Text(
                                text = title,
                                color =
                                Color.White.copy(
                                    alpha = if (isSelected) 1f else 0.7f
                                ),
                                fontSize = if (isSelected) 18.sp else 16.sp,
                                fontWeight =
                                if (isSelected) FontWeight.Bold
                                else FontWeight.Normal
                            )
                        },
                        selected = pagerState.currentPage == index,
                        onClick = { scope.launch { pagerState.scrollToPage(index) } },
                    )
                }
            }
            //        Text("here", modifier = Modifier.background(Color.Black).fillMaxWidth())
            HorizontalPager(state = pagerState, modifier = Modifier.fillMaxWidth()) { page: Int ->
                when (page) {
                    0 -> LatestPage()
                    1 -> PopularPage()
                    2 -> FavoritesPage()
                }
            }
        } else {
            SearchPage()
        }
    }
    // 悬浮按钮
    FloatingActionButton(
        onClick = { /* 跳转到发帖页面  CreatePost()*/
            navController.navigate("createPost")
        },
        modifier =
        Modifier
            .padding(16.dp) // 按钮距离屏幕边缘的距离
            .offset {
                IntOffset(fabPosition.x.toInt(), fabPosition.y.toInt())
            } // 设置按钮的位置
            .pointerInput(Unit) {
                detectDragGestures { _, dragAmount ->
                    // 更新按钮的位置
                    fabPosition =
                        Offset(
                            fabPosition.x + dragAmount.x,
                            fabPosition.y + dragAmount.y
                        )
                }
            },
        shape = RoundedCornerShape(50),
        containerColor = Cyan
    ) { Icon(imageVector = Icons.Default.Add, contentDescription = "添加帖子", tint = Color.White) }
}
